package com.liu.community.controller;/*
 *@Author:Liu Xing-zhi
 *Description:  授权登录
 *Date:Crated in 14:01 2021/9/30
 */

import com.alibaba.fastjson.JSONObject;
import com.liu.community.dto.GitteeUser;
import com.liu.community.pojor.User;
import com.liu.community.server.UserService;
import com.liu.community.utils.GitteeHttpClient;
import com.liu.community.utils.URLUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.UUID;
@Controller
@Slf4j  //注解在类上，为类生成一个日志对象
public class AuthorizeController {

    //从application.properties获取gitee参数。
    @Value("${gitee.oauth.clientid}")
    public String CLIENTID;
    @Value("${gitee.oauth.clientsecret}")
    public String CLIENTSECRET;
    @Value("${gitee.oauth.callback}")
    public String URL;
    @Autowired
    private UserService userService;
    /**
     * 请求授权页面
     */
    @GetMapping(value = "/gitee/auth")
    public  String auth(HttpSession session){
        // 用于第三方应用防止CSRF攻击
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        session.setAttribute("state",uuid);
        //获取Authorization Code
        String url = "https://gitee.com/oauth/authorize?response_type=code" +
                "&client_id=" + CLIENTID +
                "&redirect_uri=" + URLEncoder.encode(URL) +
                "&state=" + uuid +
                "&scope=user_info";
        //重定向到gitee请求授权。
        return URLUtils.sendRedirectTo(url);
    }

    //授权回调
    @GetMapping(value = "/login")
    public  String callback(@RequestParam(name = "state") String state,
                            @RequestParam(name = "code")String code,
                            HttpSession session,
                            HttpServletResponse response) throws IOException {
        String uuId = (String) session.getAttribute("state");
        //验证发的验证码
        if (uuId != null){
            //验证码不为空
            if (!uuId.equals(state)){
                //验证码不匹配,返回登录页面
                URLUtils.sendRedirectTo("/login");
            }
        }
        //定义向码云认证服务器发送post请求传入 用户授权码 以及 回调地址
        String url = "https://gitee.com/oauth/token?grant_type=authorization_code" +
                "&client_id=" + CLIENTID +
                "&client_secret=" + CLIENTSECRET +
                "&code=" + code +
                "&redirect_uri=" + URL;
        //获取token
        JSONObject token = GitteeHttpClient.getAccessToken(url);
        //获取用户信息
        url = "https://gitee.com/api/v5/user?access_token=" + token.get("access_token");
        GitteeUser userInfo = GitteeHttpClient.getUserInfo(url);
        //System.out.println(userInfo);
        if (userInfo != null && userInfo.getId() != null){
            String accountId = String.valueOf(userInfo.getId());
            String userToken = UUID.randomUUID().toString();
                User user = new User();
                user.setToken(userToken);
                user.setName(userInfo.getName());
                user.setAccountId(accountId);
                user.setAvatarUrl(userInfo.getAvatar_url());
                userService.createOrUpdateUser(user);
            //用户信息不为空，可以保存session以及cookie
            //写入cookie
            response.addCookie(new Cookie("token",userToken));
            //重定向到首页，不显示地址栏其他信息。
            return  URLUtils.sendRedirectTo("/index");
        }else {
            //输出日志信息
            log.debug("userInfo is null ,it is error ,{}",userInfo);
            //用户信息为空，返回登录页面。
            return  URLUtils.sendRedirectTo("/index");
        }
    }

    @GetMapping("/logOut")
    public  String logOut(HttpServletRequest request,HttpServletResponse response){
        //request.getSession().invalidate();//清除所有session信息
        request.getSession().removeAttribute("user");//清除指定session信息属性
        //清除cookie
        Cookie cookie = new Cookie("token",null);
        cookie.setMaxAge(0);
        response.addCookie(cookie);
        return  URLUtils.sendRedirectTo("/index");
    }
}
